extends Node

var listener: TCPServer
var client: StreamPeerTCP = null

func _ready():
	listener = TCPServer.new()
	var err = listener.listen(12345)
	if err != OK:
		print("监听失败: ", err)
		return
	print("Godot 正在监听端口 12345")

func _process(_delta):
	# 检查是否有新的客户端连接
	if listener.is_connection_available():
		client = listener.take_connection()
		if client:
			print("客户端已连接")

	# 如果已有客户端连接，持续读取数据
	if client and client.get_status() == StreamPeerTCP.STATUS_CONNECTED:
		while client.get_available_bytes() > 0:
			var data = client.get_utf8_string(client.get_available_bytes())
			print(data)

	# 如果客户端断开连接，重置 client
	if client and client.get_status() == StreamPeerTCP.STATUS_ERROR:
		print("客户端断开连接")
		client = null
